<?php

namespace common\helpers;


class Util
{
    /**
     * 异常字符串
     * @param \Throwable $e
     * @param bool $isTrace
     * @return string
     */
    public static function exceptionToString(\Throwable $e,$isTrace = true)
    {
        $baseMsg = "{$e->getFile()} line:{$e->getLine()} code:{$e->getCode()} message:{$e->getMessage()}";
        $trace = $isTrace ? $e->getTraceAsString() : '';
        return "{$baseMsg} {$trace}";
    }


    /**
     * curl 请求
     * @param string $url
     * @param string $method
     * @param array $data
     * @param array $headers
     * @param string $encoding
     * @param int $timeout
     * @return mixed
     * @throws \Exception
     */
    public static function subCurl($url, $method = 'GET', $data = null, $headers = [], $encoding = null, $timeout = 30)
    {
        $method = strtoupper($method);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if(!empty($headers)){
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        if(!empty($encoding)){
            curl_setopt($ch, CURLOPT_ENCODING, $encoding);
        }
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        $result = curl_exec($ch);
        if($result === false){
            throw new \Exception('Curl error :['.$url.']['.curl_errno($ch).'] '.curl_error($ch));
        }
        curl_close($ch);
        return $result;
    }



}